#include "gd32l23x.h"
#include "stdint.h"
#include "stdio.h"
#include "version.h"
#include "cpuusage.h"

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "timers.h"

#include "DevicesADC.h"
#include "DevicesKey.h"
#include "DevicesLed.h"
#include "DevicesQueue.h"
#include "DevicesTime.h"

#include "taskSoftTimer.h"


TimerHandle_t g_xTimersLedHandle = NULL;    /* Led定时刷新定时器 */
TimerHandle_t g_xTimersKeyHandle = NULL;    /* Key定时读取定时器 */
TimerHandle_t g_xTimersPrintHandle = NULL;  /* 打印定时读取定时器 */


/*
*   函 数 名: vSoftTimerLedCallback
*   功能说明: 定时器led回调函数
*   形    参: 无
*   返 回 值: 无
*/
static void vSoftTimerLedCallback(xTimerHandle pxTimer)
{
    (void)pxTimer;

    vLedMachine();
}

/*
*   函 数 名: vSoftTimerKeyCallback
*   功能说明: 定时器key回调函数
*   形    参: 无
*   返 回 值: 无
*/
static void vSoftTimerKeyCallback(xTimerHandle pxTimer)
{
    (void)pxTimer;

    /* 有触发了新按键状态 */
    if(enumKeyStateMachine(&g_typeKey) != keyNormal)
    {
        /* 把有效的按键数据存入FIFO */
        enumQueuePushDatas(&g_TypeQueueKeyInput, &g_typeKey, sizeof(g_typeKey));
    }
}

/*
*   函 数 名: vSoftTimerPrintCallback
*   功能说明: 定时器Print回调函数
*   形    参: 无
*   返 回 值: 无
*/
static void vSoftTimerPrintCallback(xTimerHandle pxTimer)
{
    (void)pxTimer;
    float fAdc[6];

    fAdc[0] = fADCGetDMAValue(ADC_DMA_SCAN_DCDC_OUT_VOLTAGE);
    fAdc[1] = fADCGetDMAValue(ADC_DMA_SCAN_DCDC_OUT_CURRENT);
    fAdc[2] = fADCGetDMAValue(ADC_DMA_SCAN_DCDC_INDUCTIVE_CURRENT);
    fAdc[3] = fADCGetDMAValue(ADC_DMA_SCAN_DCDC_B_INDUCTIVE_CURRENT);
    fAdc[4] = fADCGetDMAValue(ADC_DMA_SCAN_DCDC_IN_VOLTAGE);
    fAdc[5] = fADCGetDMAValue(ADC_DMA_SCAN_DCDC_TEMPERATURE);

    printf("%s - %.3f%%\r\n", pcStampToDateTimeStrings(lTimestampGet() / 1000000), fCPUUsageGet() * 100.0f);
    printf("ADC PA0: %.3f, PA1: %.3f, PA2: %.3f, PA4: %.3f, PA6: %.3f, PA7: %.3f\r\n", fAdc[0], fAdc[1], fAdc[2], fAdc[3], fAdc[4], fAdc[5]);
}

/*
*   函 数 名: cSoftTimerInit
*   功能说明: 操作系统软件定时器初始化
*   形    参: 无
*   返 回 值: 错误值
*/
int8_t cSoftTimerInit(void)
{
    /*创建定时器*/
    g_xTimersLedHandle      = xTimerCreate("Timer led",     20 / portTICK_RATE_MS,   pdTRUE, (void*)NULL, vSoftTimerLedCallback);
    xTimerStart(g_xTimersLedHandle, 200);

    g_xTimersKeyHandle      = xTimerCreate("Timer key",     20 / portTICK_RATE_MS,   pdTRUE, (void*)NULL, vSoftTimerKeyCallback);
    xTimerStart(g_xTimersKeyHandle, 200);

    g_xTimersPrintHandle    = xTimerCreate("Timer Print",   1000 / portTICK_RATE_MS, pdTRUE, (void*)NULL, vSoftTimerPrintCallback);
    xTimerStart(g_xTimersPrintHandle, 200);

    return 0;
}
